package com.tb.service.impl;

import com.tb.mapper.UserMapper;
import com.tb.pojo.User;
import com.tb.service.AllService;
import com.tb.service.UserService;
import com.tb.utils.SaltUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl extends AllService implements UserService {

    @Autowired
    private UserMapper um;


    @Override
    public User register(User user) {
        String salt = SaltUtils.getSalt(8);
        Md5Hash hash = new Md5Hash(user.getPassword(), salt, 1024);
        user.setPassword(hash.toHex());
        user.setSalt(salt);
        /*需要返回一个 对应的id 根据id 来生成工号*/
        int i = um.addUser(user);
        Integer id = user.getId();
        if (id != null && i == 1) {
            return user;
        }
        return null;
    }

    @Override
    public boolean login(String username, String password) {
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(new UsernamePasswordToken(username, password));
        } catch (Exception e) {
            throw e;
        }
        /*认证完成了才能进行授权*/
        return true;
    }

    @Override
    public void loginOut() {
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.logout();
        } catch (Exception e) {
            throw e;
        }
    }
}

